package situ.com.musicplayer;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";

    private static final int REQUEST_PERMISSION_CODE = 123;

    private ListView mListView;
    private FileAdapter mFileAdapter;

    // 当前的正在展示的目录
    private File mCurrentDirectory;

    // 要获取的读写SDcard的权限
    private static String[] PERMISSIONS_STORAGE = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mListView = (ListView) findViewById(R.id.listView);

        //获取读写权限
        getPermission();

        // 返回SDCard的根目录
        // java里面的File既可以是文件也可以是文件夹
        mCurrentDirectory = Environment.getExternalStorageDirectory();
        // 列出当前文件夹下面所有的文件
        File[] files = mCurrentDirectory.listFiles();
        for(File f : files) {
            Log.d(TAG, f.getAbsolutePath());
        }

        mFileAdapter = new FileAdapter(files);
        mListView.setAdapter(mFileAdapter);

    }

    //获取权限
    private void getPermission() {
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, PERMISSIONS_STORAGE, REQUEST_PERMISSION_CODE);
            }
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // 监听Back按键
        if (event.getAction() == KeyEvent.ACTION_DOWN
                && event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
            if (mCurrentDirectory.equals(Environment.getExternalStorageDirectory())) {
                // 当前已经是SDCard的根目录，按了back按键之后直接销毁这个Activity
                setResult(RESULT_CANCELED);
                // 销毁Activity
                finish();
                return  true;
            }

            // 当按了back按键之后获得当前目录的上一级目录
            mCurrentDirectory = mCurrentDirectory.getParentFile();
            // 列出点击的目录下面所有的文件
            File[] files = mCurrentDirectory.listFiles();
            // 更新Adapter展示的数据
            mFileAdapter.setData(files);
            // 对于Adapter改动数据需要调用刷新的操作
            mFileAdapter.notifyDataSetChanged();

            return  true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private class FileAdapter extends BaseAdapter{

        private File[] files;

        // Adapter需要的数据初始可以通过构造方法传递过来
        public FileAdapter(File[] files) {
            this.files = files;
        }

        // 后期数据改动，可以通过setData修改数据
        public void setData(File[] files) {
            this.files = files;
        }

        @Override
        public int getCount() {
            return files.length;
        }

        @Override
        public Object getItem(int position) {
            return files[position];
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHoder viewHolder;
            if (convertView == null) {
                viewHolder = new ViewHoder();
                convertView = LayoutInflater.from(getApplicationContext()).inflate(R.layout.list_item, parent, false);
                viewHolder.fileIconImageView = (ImageView) convertView.findViewById(R.id.iv_file_icon);
                viewHolder.fileNameTextView = (TextView) convertView.findViewById(R.id.tv_file_name);
                convertView.setTag(viewHolder);
            } else {
               viewHolder = (ViewHoder) convertView.getTag();
            }

            final File file = files[position];
            // 获得文件的名字
            final String fileNmae = file.getName();
            viewHolder.fileNameTextView.setText(fileNmae);
            if (file.isDirectory()){ // 返回true代表是文件夹
                viewHolder.fileIconImageView.setBackgroundResource(R.drawable.folder);
            } else {
                viewHolder.fileIconImageView.setBackgroundResource(R.drawable.file);
            }

           // 给ListView添加点击事件
            convertView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (file.isDirectory()) {// 点击的是目录（文件夹）
                        mCurrentDirectory = file;
                        // 列出点击的目录下面所有的文件
                        File[] files = mCurrentDirectory.listFiles();
                        // 更新Adapter展示的数据
                        mFileAdapter.setData(files);
                        // 对于Adapter改动数据需要调用刷新的操作
                        mFileAdapter.notifyDataSetChanged();
                    } else if (file.isFile() && file.getName().endsWith(".mp3")) {
                        // 如果是mp3文件
                        Intent intent = new Intent(MainActivity.this, MusicPlayerActivity.class);
                        intent.putExtra("path", file.getPath());
                        ArrayList<String> mp3List = getMap3List(mCurrentDirectory);
                        intent.putExtra("mp3List", mp3List);
                        startActivity(intent);
                    } else {
                        // 非mp3文件
                        Toast.makeText(MainActivity.this, "不支持该文件类型", Toast.LENGTH_LONG).show();
                    }

                }

                // 获得当前文件夹下面所有的mp3歌曲
                private ArrayList<String> getMap3List(File directory) {
                    File[] files = directory.listFiles();
                    ArrayList<String> list = new ArrayList<String>();
                    for (File file : files) {
                        if (file != null && file.isFile() && file.getName().endsWith(".mp3")) {
                            list.add(file.getPath());
                        }
                    }

                    return list;
                }
            });


            return convertView;
        }

    }
    private class ViewHoder{
        public ImageView fileIconImageView;
        public TextView fileNameTextView;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_PERMISSION_CODE) {
            for (int i = 0; i < permissions.length; i++) {
                Log.i("MainActivity", "申请的权限为：" + permissions[i] + ",申请结果：" + grantResults[i]);
            }
        }
    }
}
